package com.ahsjdy.st.stservice.service.impl;

import com.ahsjdy.st.stdao.entity.Navigation;
import com.ahsjdy.st.stdao.mapper.NavigationMapper;
import com.ahsjdy.stcommon.dto.NavigationDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class NavServiceImpl {

    @Autowired
    private NavigationMapper navigationMapper;

    public void addNav(String name, int level, Integer parentId, String price, String remark) {

        Navigation navigation = new Navigation();
        navigation.setLevel(level);
        navigation.setNavname(name);
        navigation.setParentId(parentId);
        navigation.setPrice(price);
        navigation.setRemark(remark);
        navigation.setStatus(1);
        navigationMapper.insert(navigation);
    }

    public List<Navigation> listFirstNav() {
        return navigationMapper.listByLevel(1);
    }

    public List<Navigation> listSecondNav(int parentId) {
        return navigationMapper.listByParent(parentId);
    }

    public void modifyNav(Integer navId, String name, String price, Integer status) {
        Navigation navigation = navigationMapper.selectByPrimaryKey(navId);
        if (!StringUtils.isBlank(name)) {
            navigation.setNavname(name);
        }

        if (!StringUtils.isBlank(price)) {
            navigation.setPrice(price);
        }

        if (null != status) {
            navigation.setStatus(status);
        }

        navigationMapper.updateByPrimaryKey(navigation);
    }

    public List<NavigationDTO> listNav() {
        List<Navigation> navigations = navigationMapper.listByLevel(1);
        List<Navigation> secondNav = navigationMapper.listByLevel(2);

        List<NavigationDTO> dtos = new ArrayList(navigations.size());

        for (Navigation nav : navigations) {
            NavigationDTO parent = new NavigationDTO();
            List<NavigationDTO> childs = new ArrayList();

            for (Navigation c : secondNav) {
                if (c.getParentId().equals(nav.getId())) {
                    NavigationDTO child = new NavigationDTO();
                    childs.add(child);

                    child.setPrice(c.getPrice());
                    child.setNavname(c.getNavname());
                    child.setLevel(c.getLevel());
                    child.setId(c.getId());
                }
            }
            parent.setChilds(childs);
            parent.setId(nav.getId());
            parent.setLevel(nav.getLevel());
            parent.setNavname(nav.getNavname());
            parent.setPrice(nav.getPrice());

            dtos.add(parent);
        }

        return dtos;
    }
}
